import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'
import Dashboard from '@/views/Dashboard/index.vue'
import { userApi } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { getSystemConfig } from '@/utils/layoutUtils'
import { normalizeRedirectPath } from '@/utils/routeUtils'

/**
 * 路由配置说明：
 * meta: {
 *   title: string,       // 菜单标题
 *   icon?: string,       // 菜单图标
 *   hidden?: boolean,    // 是否在菜单中隐藏
 *   activeMenu?: string, // 自定义菜单激活路径
 *   breadcrumb?: boolean,// 是否显示在面包屑中
 *   noRedirect?: boolean,// 在面包屑中禁止点击跳转
 *   parent?: string,     // 指定父级路由，用于生成面包屑
 *   type?: string        // 页面类型：list-列表页，detail-详情页，form-表单页
 * }
 */
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
    meta: { hidden: true },
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '系统首页',
          icon: 'DataAnalysis',
        },
      },
      {
        path: '/publish',
        name: 'Publish',
        component: () => import('@/views/Publish/index.vue'),
        meta: {
          title: '发布文章',
          icon: 'EditPen',
        },
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/Layout/components/Profile.vue'),
        meta: {
          title: '个人信息',
          icon: 'User',
          hidden: true, // 在侧边栏中隐藏
        },
      },
    ],
  },
  {
    path: '/article',
    component: Layout,
    redirect: '/article/list',
    meta: {
      title: '文章管理',
      icon: 'Reading',
    },
    children: [
      {
        path: 'list',
        name: 'ArticleList',
        component: () => import('@/views/Article/list/index.vue'),
        meta: {
          title: '文章列表',
        },
      },
      {
        path: 'edit',
        name: 'ArticleEdit',
        component: () => import('@/views/Publish/index.vue'),
        meta: {
          title: '编辑文章',
          hidden: true,
          parent: 'ArticleList',
          activeMenu: '/article/list',
        },
      },
      {
        path: 'add',
        name: 'ArticleAdd',
        component: () => import('@/views/Publish/index.vue'),
        meta: {
          title: '新增文章',
          hidden: true,
          parent: 'ArticleList',
          activeMenu: '/article/list',
        },
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/Article/category/index.vue'),
        meta: { title: '分类管理' },
      },
      {
        path: 'tag',
        name: 'Tag',
        component: () => import('@/views/Article/tag/index.vue'),
        meta: { title: '标签管理' },
      },
      {
        path: 'preview/:id',
        name: 'ArticlePreview',
        component: () => import('@/views/Article/preview/index.vue'),
        meta: {
          title: '文章预览',
          hidden: true,
          parent: 'ArticleList',
          activeMenu: '/article/list',
        },
      },
    ],
  },
  {
    path: '/information',
    component: Layout,
    redirect: '/information/source',
    meta: {
      title: '信息管理',
      icon: 'Collection',
    },
    children: [
      {
        path: 'source',
        name: 'Source',
        component: () => import('@/views/Information/source/index.vue'),
        meta: { title: '素材管理' },
      },
      {
        path: 'album',
        name: 'Album',
        component: () => import('@/views/Information/album/index.vue'),
        meta: { title: '相册管理' },
      },
      {
        path: 'comments',
        name: 'Comments',
        component: () => import('@/views/Information/comments/index.vue'),
        meta: { title: '评论管理' },
      },
      {
        path: 'links',
        name: 'Links',
        component: () => import('@/views/Information/links/index.vue'),
        meta: { title: '链接管理' },
      },
    ],
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/configuration',
    meta: {
      title: '系统设置',
      icon: 'Setting',
    },
    children: [
      {
        path: 'configuration',
        name: 'Configuration',
        component: () => import('@/views/System/configuration/index.vue'),
        meta: { title: '基础配置' },
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/System/user/index.vue'),
        meta: { title: '用户管理' },
      },
      {
        path: 'dictionary',
        name: 'Dictionary',
        component: () => import('@/views/System/dictionary/index.vue'),
        meta: { title: '字典管理' },
      },
      {
        path: 'notice',
        name: 'Notice',
        component: () => import('@/views/System/notice/index.vue'),
        meta: { title: '公告管理' },
      },
      {
        path: 'sensitive',
        name: 'Sensitive',
        component: () => import('@/views/System/sensitive/index.vue'),
        meta: { title: '敏感词管理' },
      },
    ],
  },
  {
    path: '/monitor',
    component: Layout,
    redirect: '/monitor/server',
    meta: {
      title: '监控中心',
      icon: 'Monitor',
    },
    children: [
      {
        path: 'server',
        name: 'Server',
        component: () => import('@/views/Monitor/server/index.vue'),
        meta: { title: '服务监控' },
      },
      {
        path: 'job',
        name: 'Job',
        component: () => import('@/views/Monitor/job/index.vue'),
        meta: { title: '定时任务' },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

const { systemName } = getSystemConfig()
/**
 * 路由守卫
 */
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ${systemName}` : systemName

  // 登录页面直接放行
  if (to.path === '/login') {
    next()
    return
  }

  const userStore = useUserStore()

  // 首次进入时强制校验一次会话状态
  if (!userStore.isSessionValidated) {
    try {
      const userInfo = await userApi.getCurrentInfo()
      userStore.setUserInfo(userInfo)
      userStore.setSessionValidated(true)
    } catch (error) {
      userStore.clearUserInfo()
      userStore.setSessionValidated(true)
      next({
        path: '/login',
        query: { redirect: normalizeRedirectPath(to.path) },
      })
      return
    }
  }

  // 已完成校验但没有用户信息，直接拦截到登录
  if (!userStore.userInfo) {
    next({
      path: '/login',
      query: { redirect: normalizeRedirectPath(to.path) },
    })
    return
  }

  next()
})

export default router
